﻿using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Peak.Core;
using Peak.Core.DataInterfaces;
using Peak.Resources;
using Peak.Web.Controllers.Models;
using Peak.Web.Controllers.Services;
using SharpArch.Web.NHibernate;
using MvcContrib;

namespace Peak.Web.Controllers
{
  public class UserController : BaseController
  {
    private readonly IUserRepository _userRepository;

    public UserController(ISessionService sessionService, IUserRepository userRepository)
      :base(sessionService)
    {
      _userRepository = userRepository;
    }

    public ActionResult Index()
    {
      return View(new UserPreferencesModel(_userRepository.GetByUserName(User.Identity.Name)));
    } 
   
    public ActionResult Edit()
    {
      return View(new UserPreferencesModel(_userRepository.GetByUserName(User.Identity.Name)));
    }

    [AcceptVerbs(HttpVerbs.Post)]
    [ValidateInput(false)]
    [Transaction]
    public ActionResult Edit(UserPreferencesModel user)
    {
      User dbUser = _userRepository.GetByUserName(User.Identity.Name);
      user.UserName = User.Identity.Name;        
      if(!user.IsValid())
      {
        return View(user);
      }      
      user.Update(dbUser);
      return this.RedirectToAction(f=>f.Index());
    }

    public ActionResult ChangePassword()
    {
      return View(new ChangePasswordModel());
    }

    [AcceptVerbs(HttpVerbs.Post)]
    [ValidateInput(false)]
    [Transaction]
    public ActionResult ChangePassword(ChangePasswordModel changePasswordModel)
    {
      if(!ModelState.IsValid)
      {
        return View(changePasswordModel);
      }      

      User dbUser = _userRepository.GetByUserName(User.Identity.Name);
      if (dbUser.Password != Core.User.EncodePassword(changePasswordModel.OldPassword))
      {
        ModelState.AddModelError<ChangePasswordModel>(f => f.OldPassword, ValidationErrors.InvalidPassword);
        return View(changePasswordModel);
      }

      dbUser.SetPassword(changePasswordModel.Password);

      return MessageBox(Messages.PasswordChangedSuccessfully);
    }
  }
}
